package edu.njust.httpmanager.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.njust.httpmanager.entity.Api;
import edu.njust.httpmanager.entity.Catalog;
import edu.njust.httpmanager.entity.dto.ApiDto;
import edu.njust.httpmanager.mapper.ApiMapper;
import edu.njust.httpmanager.mapper.CatalogMapper;
import edu.njust.httpmanager.service.IApiService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
* @author Goal
* @description 针对表【api(接口)】的数据库操作Service实现
* @createDate 2023-09-03 16:50:57
*/
@Service
public class ApiServiceImpl extends ServiceImpl<ApiMapper, Api>
    implements IApiService {

    @Resource
    private ApiMapper apiMapper;

    @Resource
    private CatalogMapper catalogMapper;

    @Override
    public List<ApiDto> getAllApi(Long programId, String sortOrder,String searchKey){

        LambdaQueryWrapper<Api> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Api::getProgramId, programId);
        //通过sortOrder判断是否要排序
        if (sortOrder != null) {
            queryWrapper.orderBy(true, sortOrder.equals("ascend"), Api::getMethod);
        }
        //通过searchKey进行搜索
        if(searchKey != null)
        {
            queryWrapper.like(true,Api::getName,searchKey);
        }
        List<Api> apis = apiMapper.selectList(queryWrapper);

        List<ApiDto> apiDtos = apis.stream().map((item)-> {
            ApiDto apiDto = new ApiDto();
            //拷贝原有属性
            BeanUtils.copyProperties(item,apiDto);

            // 获取目录id
            Long catalogId = item.getCatalogId();
            //查询catalog
            Catalog catalog = catalogMapper.selectById(catalogId);
            //封装进apiDto
            apiDto.setCatalogName(catalog.getName());
            //返回结果
            return apiDto;


        }).collect(Collectors.toList());
        return apiDtos;
    }
}




